<template>
  <el-dialog
    v-toggle-full
    class="base-dialog"
    :custom-class="'panna-dialog_big'"
    :append-to-body="true"
    title="盘点单处理"
    align="center"
    :close-on-click-modal="false"
    :visible.sync="dialogOperateVisible"
    @closed="closeDialog"
  >
    <div v-loading.lock="loading" class="base-view">
      <el-descriptions title="基础信息" direction="vertical" :column="7" border>
        <el-descriptions-item label="盘点单编号">{{
          formData.checkNum
        }}</el-descriptions-item>
        <el-descriptions-item label="盘点仓库">{{
          formData.storageName
        }}</el-descriptions-item>
        <el-descriptions-item label="库区范围" :span="2">{{
          formData.storageAreaRangeName
        }}</el-descriptions-item>
        <el-descriptions-item label="盘点负责人">{{
          formData.operatorName
        }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{
          formData.remark
        }}</el-descriptions-item>
      </el-descriptions>
      <div class="mid">
        <el-button type="primary" size="small" @click="exportExcel"
          >导出盘点清单</el-button
        >
        <el-button class="btn" type="primary" size="small" @click="importData"
          >导入盘点清单</el-button
        >
        <el-button class="btn" type="danger" size="small" @click="clearData"
          >清空盘点结果</el-button
        >
      </div>
      <el-descriptions title="盘点结果" class="labelClassName">
        <template slot="extra">
          <el-checkbox v-model="checked" @change="filterResult"
            >只显示盘点差异数据</el-checkbox
          >
        </template>
      </el-descriptions>
      <el-table
        ref="tableResult"
        :data="
          filterFormResult.slice(
            (pagination.pageIndex - 1) * pagination.pageSize,
            pagination.pageIndex * pagination.pageSize
          )
        "
        style="height: 500px; width: 100%"
        highlight-current-row
      >
        <el-table-column label="库区">
          <template slot-scope="scope">
            {{ scope.row.storageAreaName }}
          </template>
        </el-table-column>

        <el-table-column label="证书编号">
          <template slot-scope="scope">
            {{ scope.row.certificateNum }}
          </template>
        </el-table-column>
        <el-table-column label="物料编号">
          <template slot-scope="scope">
            {{ scope.row.productNum }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称">
          <template slot-scope="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column label="分类">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>

        <el-table-column label="型号规格">
          <template slot-scope="scope">
            {{ scope.row.size }}
          </template>
        </el-table-column>
        <el-table-column label="包装单位">
          <template slot-scope="scope">
            {{ scope.row.packingUnit }}
          </template>
        </el-table-column>
        <el-table-column label="存储条件">
          <template slot-scope="scope">
            {{ scope.row.storeCondition }}
          </template>
        </el-table-column>
        <el-table-column label="实际库存">
          <template slot-scope="scope">
            {{ scope.row.actualStock }}
          </template>
        </el-table-column>
        <el-table-column label="盘点库存">
          <template slot-scope="scope">
            {{ scope.row.checkStock }}
          </template>
        </el-table-column>
        <el-table-column label="差异库存">
          <template slot-scope="scope">
            <span :class="scope.row.differenceStock >= 0 ? 'red' : 'green'">{{
              scope.row.differenceStock > 0
                ? '+' + scope.row.differenceStock
                : scope.row.differenceStock
            }}</span>
          </template>
        </el-table-column>
      </el-table>
      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
      <el-descriptions title="盘点备注" class="labelClassName">
      </el-descriptions>
      <el-input
        v-model="formData.checkRemark"
        type="textarea"
        :autosize="{ minRows: 4, maxRows: 4 }"
        placeholder="请输入备注"
      >
      </el-input>
      <div style="padding-top: 10px">
        <el-button type="primary" @click="handle(false)">保存</el-button>
        <el-button type="primary" @click="handle(true)">保存并提交</el-button>
      </div>
    </div>
    <ImportComponents
      ref="ImportComponents"
      v-model="importVisible"
      :show-download="false"
      @success="cancelImport"
      @UploadMethod="UploadMethod"
    />
  </el-dialog>
</template>

<script>
import { get, handle, getCheckDataList, exportInventoryCheckList } from "../../../api/Material/MaterialInventoryCheck.js";
import { export_json_to_excel } from "@/vendor/Export2Excel"
export default {
  name: "InventoryOperate",
  components: {},
  props: {
    dialogOperateVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: '0',
    }
  },
  data() {
    return {
      importVisible: false,
      tHeader: [
        "仓库",
        "库区",
        "证书编号",
        "物料编号",
        "物料名称",
        "型号规格",
        "实际库存",
        "盘点库存",

      ],
      filterVal: [
        "storageName",
        "storageAreaName",
        "certificateNum",
        "productNum",
        "productName",
        "size",
        "actualStock",
        "checkStock"],
      loading: false,
      checked: true,
      formData: {},
      formResult: [],
      filterFormResult: [],
      checkDetails: [],
      count: 0,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      get({ id: this.editId }).then(res => {
        this.formData = res.data;
        this.formResult = res.data.inventoryCheckDetailsList;
        this.filterResult()
      }).catch(res => { })
    },
    // 保存&保存并提交
    handle(isSubmit) {
      if (this.formResult === null || this.formResult.length === 0) {
        this.$message.error("请导入盘点清单");
        return false;
      }
      var data = {};
      data.isSubmit = isSubmit;
      data.id = this.editId;
      data.checkRemark = this.formData.checkRemark;
      this.checkDetails = [];
      for (var i = 0; i < this.formResult.length; i++) {
        var obj = {
          checkId: this.editId,
          productId: this.formResult[i].productId, // 物料ID
          productNum: this.formResult[i].productNum, // 物料编号
          productName: this.formResult[i].productName, // 物料名称
          storageAreaId: this.formResult[i].storageAreaId, // 库区Id
          storageAreaName: this.formResult[i].storageAreaName, // 库区
          storageSpaceId: this.formResult[i].storageSpaceId, // 没有库位概念
          storageSpaceName: this.formResult[i].storageSpaceName, // 没有库位概念
          certificateNum: this.formResult[i].certificateNum, // 证书编号
          type: this.formResult[i].type, // 产品分类
          size: this.formResult[i].size, // 型号规格
          packingUnit: this.formResult[i].packingUnit, // 包装单位
          storeCondition: this.formResult[i].storeCondition, // 存储条件
          actualStock: this.formResult[i].actualStock,
          checkStock: this.formResult[i].checkStock,
          differenceStock: this.formResult[i].differenceStock
        };
        if (this.formResult[i].dateManufacture !== '') {
          obj.dateManufacture = this.formResult[i].dateManufacture
        }
        if (this.formResult[i].supplierId !== '') {
          obj.supplierId = this.formResult[i].supplierId
        }
        if (this.formResult[i].supplierName !== '') {
          obj.supplierName = this.formResult[i].supplierName
        }
        this.checkDetails.push(obj)
      }
      data.inventoryCheckDetails = this.checkDetails;
      // 调用处理api
      handle(data).then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.$emit("update:dialogOperateVisible", false);
          this.$parent.getListFun();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => { });
    },
    clearData() {
      this.formResult = [];
      this.filterFormResult = [];
    },
    filterResult() {
      this.pagination.pageIndex = 1;
      if (this.checked) {
        this.filterFormResult = this.formResult.filter((item) => {
          return item.differenceStock !== 0
        })
      } else {
        this.filterFormResult = this.formResult;
      }
      this.pagination.total = this.filterFormResult.length;
    },
    // 上传
    UploadMethod(formData, fileCount) {
      formData.append('checkId', this.editId);
      exportInventoryCheckList(formData).then((res) => {
        if (res.code === 200) {
          // 调用上传成功方法
          this.$refs.ImportComponents.successfulOperation();
          this.$nextTick(() => {
            this.formResult = res.data;
            this.filterResult()
          })
        } else {
          this.count = 0;
          this.$message.error(res.msg);
        }
      });
    },
    // 导入
    importData() {
      this.importVisible = true;
    },
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    cancel() {
      this.$emit("update:dialogOperateVisible", false);
    },
    cancelImport() {
      this.importVisible = false;
    },
    closeDialog() {
      this.cancel();
    },
    exportExcel() {
      var storageAreaIdList = this.formData.storageAreaRange.split(',');
      getCheckDataList({ storageAreaIdList }, { pageIndex: 1, pageSize: 10000 }).then(res => {
        const data = this.formatJson(this.filterVal, res.data.dataList);
        const filename = "盘点清单" + this.formData.checkNum;
        this.export_json_to_excel({
          header: this.tHeader, // 表头
          data, // 数据
          filename: filename, // 导出文件名
          autoWidth: true, // 导出宽度自动
          bookType: "xlsx", // 导出后缀
        });
      }).catch(res => { });
    },
    changePage(val) {
      this.pagination.pageIndex = val;
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
    },
  },
};
</script>
<style  lang="scss" >
.base-view {
  display: flex;
  flex-direction: column;

  .red {
    color: red;
  }

  .green {
    color: green;
  }

  .mid {
    display: flex;
    padding: 10px 0px 0px 0px;
  }

  .btn {
    margin-left: 10px;
  }

  .labelClassName {
    padding-top: 10px;

    .el-descriptions__header {
      justify-content: left !important;

      .el-descriptions__extra {
        padding-left: 10px !important;
      }
    }
  }
}
</style>
